package com.rural.bus.driver.fragment;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.rural.bus.driver.MainActivity;
import com.rural.bus.driver.MyApplication;
import com.rural.bus.driver.OrderDealActivity;
import com.rural.bus.driver.OrderDetailActivity;
import com.rural.bus.driver.R;
import com.rural.bus.driver.adapter.MyOrderAdapter;
import com.rural.bus.driver.config.BusConstant;
import com.rural.bus.driver.config.MyPreferenceManager;
import com.rural.bus.driver.config.PreferenceKey;
import com.rural.bus.driver.model.Order;
import com.rural.bus.driver.net.MyHttpUtil;
import com.rural.bus.driver.net.OnNetCallback;
import com.rural.bus.driver.net.Url;
import com.rural.bus.driver.service.DistanceService;
import com.rural.bus.driver.view.CommonAlertDialog;
import com.rural.bus.driver.view.OrderCancelDialog;
import com.rural.bus.driver.view.CommonAlertDialog.OnDialogDismissListener;
import com.rural.bus.driver.view.OrderCancelDialog.OnDialogButtonListener;
import com.rural.bus.driver.view.OrderCompleteChargeDialog;
import com.rural.bus.driver.view.xlist.XListView;
import com.rural.bus.driver.view.xlist.XListView.IXListViewListener;

public class MyOrderFragment extends BaseFragment implements IXListViewListener, OnItemClickListener {

	private XListView listview;
	private List<Order> mOrders = new ArrayList<Order>();
	private MyOrderAdapter mAdapter;

	private String userId;
	private int mStartIndex;
	public static boolean isFresh = true;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_my_order, container, false);
		initViewAndData(view);
		return view;
	}

	private void initViewAndData(View view) {
		userId = MyApplication.driverInfo.drivId;

		listview = (XListView) view.findViewById(R.id.listview);
		listview.setPullRefreshEnable(true);
		listview.setPullLoadEnable(true);
		listview.setXListViewListener(this);
		listview.setOnItemClickListener(this);

		mAdapter = new MyOrderAdapter(getActivity(), mOrders);
		listview.setAdapter(mAdapter);

		IntentFilter filter_system = new IntentFilter();
		filter_system.addAction(BusConstant.ACTION_NEW_ORDER);
		getActivity().registerReceiver(newOrderReceiver, filter_system);
		
	}

	@Override
	public void onResume() {
		super.onResume();
		if (isFresh) {
			isFresh = false;
			mStartIndex = 0;
			getMyOrderList();
		}
	}

	private void getMyOrderList() {
		if (TextUtils.isEmpty(userId)) {
			return;
		}
		MyHttpUtil myHttpUtil = new MyHttpUtil();
		myHttpUtil.addBodyParm("udid", userId);
		myHttpUtil.addBodyParm("type", "1");
		myHttpUtil.addBodyParm("start", "" + mStartIndex);
		myHttpUtil.addBodyParm("end", "" + BusConstant.PAGE_SIZE);
		myHttpUtil.send(Url.orderlist_in_url, new OnNetCallback() {

			@Override
			public void success(JSONObject object) {
				listview.stopRefresh();
				listview.stopLoadMore();
				try {
					if (object.get("status").equals("0")) {
						JSONArray array = object.getJSONArray("result");
						if (mStartIndex == 0) {
							mOrders.clear();
						}
						if (mStartIndex != 0 && array.length() == 0) {
							toast("别拉了，没订单了");
						} else {
							int i = 0;
							while (i < array.length()) {
								Order order = Order.parse(array.getJSONObject(i));
								mOrders.add(order);
								i++;
							}
							mAdapter.notifyDataSetChanged();
							//如果存在运行中的订单，则继续计算公里数
							if(judgeIsExistInServiceOrder()){
								Intent intentService = new Intent(getActivity(), DistanceService.class);
								getActivity().startService(intentService);
							}
						}

					} else {
						toast(R.string.data_error);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void fail(String error) {
				listview.stopRefresh();
				listview.stopLoadMore();
			}
		});
	}

	@Override
	public void onRefresh() {
		mStartIndex = 0;
		getMyOrderList();
		writeLocationToFile("哈哈哈");
		
	}
	
	private void writeLocationToFile(String ss) {

		String path = Environment.getExternalStorageDirectory().getPath() + File.separator + "location";
		Log.d("bus", path);
		File file = new File(path);
		String fileName = "location2.txt";
		if (!file.exists()) {
			file.mkdirs();
		}
		File file2 = new File(path, fileName);
		if (!file2.exists()) {
			try {
				file2.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		FileWriter fileWriter = null;
		try {
			fileWriter = new FileWriter(file2, true);

			StringBuffer sb = new StringBuffer();
			sb.append(System.currentTimeMillis() + "----");
			sb.append("当前行程：" + ss + "\n");

			fileWriter.write(sb.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fileWriter != null) {
					fileWriter.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	@Override
	public void onLoadMore() {
		mStartIndex += BusConstant.PAGE_SIZE + 1;
		getMyOrderList();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if (position > 0 && position <= mOrders.size()) {
			if (mOrders.get(position - 1).orderStatus == 5) {
				CommonAlertDialog dialog = new CommonAlertDialog(getActivity(), "哦", null, "请耐心等待乘客支付", new OnDialogDismissListener() {

					@Override
					public void onConfirmClicked() {

					}

					@Override
					public void onCancelClicked() {
						// TODO Auto-generated method stub

					}
				});
				dialog.show();
			} else {
				Intent intent = new Intent(getActivity(), OrderDetailActivity.class);
				intent.putExtra("order_id", mOrders.get(position - 1).orderId);
				startActivity(intent);
			}
		}

	}

	private BroadcastReceiver newOrderReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			Log.e("MainActivity", "接收自定义动态注册广播消息");
			if (intent.getAction().equals(BusConstant.ACTION_NEW_ORDER)) {
				toast("新订单来了");
			}
		}
	};

	public void showCancelOrderDialog(Order order) {
		OrderCancelDialog orderCancelDialog = new OrderCancelDialog(getActivity(), order, new OnDialogButtonListener() {
			@Override
			public void onConfirmClicked() {
				mStartIndex = 0;
				getMyOrderList();
			}
		});
		orderCancelDialog.show();
	}

	public void showCompleteCharge(Order order) {
		OrderCompleteChargeDialog orderChargeDialog = new OrderCompleteChargeDialog(getActivity(), order, new OrderCompleteChargeDialog.OnDialogButtonListener() {
			@Override
			public void onConfirmClicked() {
				mStartIndex = 0;
				getMyOrderList();
			}
		});
		orderChargeDialog.show();
	}

	public boolean judgeIsExistInServiceOrder() {
		boolean result = false;
		for (Order order : mOrders) {
			if (order.orderStatus == 3) {
				result = true;
			}
		}
		return result;
	}
}
